package com.hdu.InheritableThreadLocalDemo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Demo4 {
    public static void main(String[] args) throws InterruptedException {
        @SuppressWarnings("all")
        ThreadLocal<Student> threadLocal = new InheritableThreadLocal() {
            @Override
            protected Object childValue(Object parentValue) {
                if (parentValue instanceof Student) {
                    Student student = (Student) parentValue;
                    Student copyStudent = new Student();
                    copyStudent.setUsername(student.getUsername());
                    return copyStudent;
                } else {
                    return super.childValue(parentValue);
                }
            }
        };
        ExecutorService executor = Executors.newFixedThreadPool(1);
        Student student = new Student();
        student.setUsername("父线程");
        threadLocal.set(student);
        executor.execute(() -> System.out.println("子线程获得值 : " + threadLocal.get()));
        TimeUnit.MILLISECONDS.sleep(500);
        student.setUsername("父进程新设置的值");
        executor.execute(() -> System.out.println("子线程获得值 : " + threadLocal.get()));
        // 子线程获得值 : Student(username=父线程)
        // 子线程获得值 : Student(username=父线程)
    }
}
